import create from '../../../utils/create2.js'
import store from '../../../store/index.js'
import PagePromoterUtil, { PagePromoter } from '../../../data/common/pagePromoter';
import { Encoder } from '../../../utils/textUtils.js';
import AppSceneUtil, {PageScene} from '../../../data/common/appScene';
import SessionUtil, { JxbHttpClient, JxbHttpInterceptor } from "../../../data/session/session"
import SystemUtil from '../../../shell/system/system.js';
import { SessionExpiredError } from '../../../utils/network.js';
import InteractionUtil from '../../../shell/ui/interaction.js';

const Common = require('../../../utils/common.js');
let pageSize = getApp().data.pageSize1;
create(store, {
  data: {
    token: '',
    list: [],
    productsList: {},
    chosenNum: 1,
    pageNo: 1,
    name: '',
    Type: '',
    isLoading: true, //加载中文字状态控制
    nomore: false, //加载更多文字状态控制
    hasMore: false,//是否还有更多
    moretext: "加载更多",
    singleStock: "",
    isShowChartChange: false,
    Details: true,
    memberIds: '',
    showBack: false,
    wh: 0,
    chosenItem: {},
    params: {
      pageSize,
      pageNo: 1,
      hideSearchStr: '',
      categoryId: '',
      type: '',
      purposeId: '',
      priceRangeId: ''
    },
    param: ''
  },
  onLoad: function (options) {
    getApp().getSaleMode()
    // 开启转发按钮
    PagePromoterUtil.showShareMenu(true).then()
    // 处理传入的参数
    let { ids, name, tag, title } = options
    if(name) name = decodeURIComponent(name)
    if(tag) tag = decodeURIComponent(tag)
    if(title) title = decodeURIComponent(title)
    let barTitle, renderData={
      pageNo: 1,
      list: [],
    };
    //扫二维码会带title参数过来
    if (title && title.length > 0) {
      barTitle = Encoder.unicodeDecode(title);
    } else if (tag) {
      barTitle = Encoder.unicodeDecode(tag);
      renderData.name = Encoder.unicodeDecode(tag);
    }
    if (name) {
      renderData.name = Encoder.unicodeDecode(name);
    }
    renderData.memberIds = ids || "";
    wx.setNavigationBarTitle({title: barTitle});
    this.setData(renderData);
    SessionUtil.getInstance().then(session => {
      // 注册当前页面的场景信息
      AppSceneUtil.setPageScene(this)
      let pageScene = new PageScene(this)
      if (pageScene.hasPromoter()) {
        this.setData({
          showBack: true
        })
      }
      this.ItemList('Refresh');
    })

  },
  onHide: function () {
    //当前顾问
    // Common.show_bar(false, this);
    this.setData({
      isShowChartChange: false
    })
  },
  onShow: function () {
    SessionUtil.getInstance().then(session => {
      // 注册当前页面的场景信息
      AppSceneUtil.setPageScene(this, false)
      this.getCartProdsList(false)
    })
  },
  //当前顾问详细信息
  show_bar: function (flag = true) {
    Common.show_bar(true, this);
  },

  updateSearchKey: function (e) {
    this.setData({
      name: e.detail.value
    })
  },
  /**关闭加入购物车弹窗 */
  hideCartpop: function (e) {
    this.setData({
      isShowChartChange: false
    })
  },
  ItemList: function (action = '') {
    // 产品列表
    var page = this;
    let { params, pageNo, name, list ,param} = page.data
    params.pageNo = pageNo
    params.hideSearchStr = name
    params.name = param
    let nowData = list
    let newData = []
    const { memberIds } = this.data
    //查询会员商品
    if (memberIds && memberIds.length > 0) {
      name = memberIds
    }
    JxbHttpClient.getClient().get({
      url: '/AppMaster/Item/ItemList',
      data: params,
    }).then(jxbResp=>{
      const { list, count, title } = jxbResp.data;
      if (list && list.length > 0) {
        if (action == 'Refresh') {
          newData = list
        } else if (action == 'Page') {
          newData = [...nowData, ...list]
        }
        let renderData = {
          list: newData
        }
        if (list.length < 10) {
          renderData.moretext= "没有更多了",
          renderData.nomore= false,
          renderData.hasMore= false;
        } else {
          renderData.moretext= "加载更多",
          renderData.pageNo= pageNo + 1,
          renderData.nomore= false,
          renderData.hasMore= true;
        }
        page.setData(renderData);
        if(title && title.length > 0){
          wx.setNavigationBarTitle({
            title: title
          })
        }
      } else { //未返回数据(接口异常)
        pageNo = -100;
        page.setData({
          nomore: false,
          moretext: "没有更多了",
        });
      }
      setTimeout(() => {
        page.setData({ isLoading: true })
      }, 1500)
    })
  },
  upper() {
    let { isLoading } = this.data
    if (!isLoading) return
    this.setData({
      pageNo: 1,
      isLoading: false
    });
    this.debounce(this.ItemList, 1000)('Refresh')
  },
  lower() {
    let { isLoading, hasMore } = this.data
    if (!isLoading) return //正在加载中
    if (!hasMore) return // 无更多数据
    var pageNo = this.data.pageNo;
    this.setData({
      pageNo: pageNo,
      isLoading: false,
      moretext: "数据加载中..."
    });
    this.debounce(this.ItemList, 1000)('Page')
  },
  goDetail: function (e) {
    var itemId = e.currentTarget.id;
    this.setData({
      Details: false,
    })
    wx.navigateTo({
      url: '/pages/product/detail/detail?itemId=' + itemId
    })
  },
  cancelCart: function () {
    var page = this;
    var isShowChartChange = page.data.isShowChartChange;
    var bIsisShowChartChange = isShowChartChange ? false : true;
    page.setData({
      isShowChartChange: bIsisShowChartChange,
      productMaskClass: bIsisShowChartChange ? "product-mask" : "",
    });
  },
  goFilter: function () {
    var page = this;
    wx.navigateTo({
      url: '/pages/product/filter/filter'
    })
  },
  AddCart: function (e) {
    var page = this;
    page.getCartProdsList();
    var ID = e.currentTarget.id
    var itemId = ID.split('-')[0];
    var stock = ID.split('-')[1];
    var chosenItem;
    var insideNum = 0;
    var acartid = '';

    if (stock < 1) {
      wx.showToast({
        title: '库存不足！',
        image: '../../images/fail.png',
        duration: 2000
      })
      return false;
    }

    page.setData({
      list_year: 0
    })
    // 显示年份
    JxbHttpClient.getClient().get({
      url: '/AppMaster/Item/getItemYearsList',
      data: {
        item_id: itemId
      }
    }).then(jxbResp=>{
      let normalInfo = jxbResp.data.item_info, list_year = jxbResp.data.item_year_list,
        activity = normalInfo.activity_category;
      if (activity != 0) {
        activity = activity.split(",");
      }
      page.setData({
        chosenItem: normalInfo,
        list_year: list_year,
        activity: activity
      })
    })
    page.setData({
      isShowChartChange: true,
      chosenNum: 1,
      singleStock: stock,
      sitemId: itemId,
      oldNum: insideNum,
      thisCartid: acartid
    });
  },
  // 点击年份切换商品
  changeYear: function (e) {
    var page = this;
    var itemId = e.currentTarget.id;
    var list_year = page.data.list_year;
    var chosenItem = page.data.chosenItem;
    if (chosenItem.item_id == itemId) {
      return false;
    } else {
      for (var i = 0; i < list_year.length; i++) {
        if (itemId == list_year[i].item_id) {
          var activity = list_year[i].activity_category;
          if (activity != 0) {
            activity = activity.split(",");
          }
          page.setData({
            chosenItem: list_year[i],
            sitemId: itemId,
            activity: activity
          })
        }
      }
    }
  },

  goCart: function () {
    var page = this;
    var num = page.data.chosenNum;//输入框的数量
    num = parseInt(num);
    JxbHttpClient.getClient().post({
      url: '/AppMaster/PosCart/PosAddCart',
      data: {
        number: num,
        itemId: page.data.sitemId
      }
    }).then(jxbResp=>{
      InteractionUtil.showSuccess('添加成功')
      page.getCartProdsList();
      page.cancelCart();
      page.setData({
        chosenNum: 1
      })
    }).catch(err=>{
      InteractionUtil.showNotice(err.message)
    })
  },
  reduceSingle: function () {
    var page = this;
    var num = page.data.chosenNum - 1;
    if (num <= 1) {
      page.setData({
        chosenNum: 1,
      })
    } else {
      page.setData({
        chosenNum: num,
      })
    }
  },
  addToCartSingle: function () {
    var page = this;
    var stock = page.data.singleStock;
    var num = page.data.chosenNum + 1;
    if (num >= stock) {
      InteractionUtil.showNotice('库存不足！')
    } else {
      page.setData({
        chosenNum: num,
      })
    }
  },
  toZero: function (e) {
    var num = e.detail.value;
    if (num.length == 0) {
      this.setData({
        chosenNum: 1
      })
    }
  },
  updateNum: function (e) {
    var num = e.detail.value;
    var tnum = parseInt(num);
    if (num.length == 0) {
      this.setData({
        chosenNum: 1
      })
    } else {
      this.setData({
        chosenNum: tnum
      })
    }
  },
  /**
   * 获取购物车商品列表
   * @param {boolean} autoRefreshToken true=会话过期时自动刷新token 
   */
  getCartProdsList: function (autoRefreshToken = true) {
    let wHeight = SystemUtil.getSystemInfo(false).windowHeight -90;
    let reqParams = {
      url:'AppMaster/PosCart/cartDetail'
    }
    if(autoRefreshToken === false){
      reqParams.interceptBizEvent = ~JxbHttpInterceptor.EVENT_TOKEN_EXPIRED & JxbHttpInterceptor.EVENT_ALL
    }
    JxbHttpClient.getClient().get(reqParams)
    .then(jxbResp=>{
      let respData=jxbResp.data, products = respData.productsList, list = respData.activity_list;
      let total = 0, gross = 0.00, itemids = [], limits = [];
      for (let z = 0; z < list.length; z++) {
        if (list[z].activity_category == 6) {
          itemids = itemids.concat(list[z].itemids);
        }
        if (list[z].activity_category == 4) {
          limits = limits.concat(list[z].itemids);
        }
      }
      for (let i = 0; i < products.length; i++) {
        total = total + products[i].carNumber;
        gross = gross + products[i].carNumber * products[i].show_price;
        let z = Common.contains(itemids, products[i].itemid),
          w = Common.contains(limits, products[i].itemid);
        if (z && w) {
          products[i].activity_list = ['秒杀', '限购']
        } else {
          if (z) {
            products[i].activity_list = ['秒杀'];
          }
          if (w) {
            products[i].activity_list = ['限购'];
          }
        }
      }
      respData.total = total;
      respData.gross = gross.toFixed(2);
      respData.productsList = products;
      let prodListLen = respData.productsList.length
      this.setData({
        productsList: respData,
        wh: prodListLen > 0 ? wHeight - 50 : wHeight
      })
    }).catch(err=>{
      if(err instanceof SessionExpiredError){
        console.log('会话过期，直接显示0', err)
        // 如果会话过期，直接显示0
        this.setData({
          total: 0,
          gross: 0,
          productMaskClass: "",
          productsList: {},
          wh: wHeight
        })
        return;
      }
      InteractionUtil.showNotice(err.message)
      this.setData({
        productMaskClass: "",
        productsList: {},
        wh: wHeight
      })
    })
  },
  goCarts: function () {
    wx.switchTab({
      url: '/pages/shoppingcart/index'
    })
  },
  clearStorageSync: function () {
    wx.setStorageSync("dilivery", '');
    wx.setStorageSync("invoice", {});
    wx.setStorageSync("pay", {});
  },
  onShareAppMessage: function () {
    let agentName = '', search = this.data.name,
      server = SessionUtil.getInstanceSync().getTheSellingServerSync()
    if(server){
      agentName = server.getTheAgentSync().showName + '酒库'
    }
    // 构造并返回自定义数据
    return (new PagePromoter( this.route, { name : search, share:1 }))
    .setShareTitle(agentName)
    .buildShareInfo()
  },
  goSearchView() {
    wx.navigateTo({
      url: '../../search/index',
    })
  },
  call(e) {
    const { phone } = e.currentTarget.dataset
    getApp().call(phone)
  },
  goBack() {
    wx.switchTab({
      url: '/pages/index/index',
    })
  },
  searchHandler(e) {
    console.log(e)
    const { detail } = e
    const { type } = detail
    let { params } = this.data
    if (type && type!==undefined) {
      params.type = type
    }
    this.setData({
      params,
      pageNo: 1,
      list: []
    })
    this.ItemList('Refresh')
  },
  onUnload() {
    this.store.data.goodsFilter = {}
    this.update()
  },
  debounce(method, delay) {
    let timer = null;
    return (args) => {
      const param = args
      const that = this
      timer && clearTimeout(timer);
      timer = setTimeout(() => {
        method.call(that, param);
      }, delay);
    }
  },
  search (e) {
    const {detail} = e
    this.setData({param: detail})
    this.ItemList('Refresh')
  }
})